package com.example.beautyUi

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.example.base.R
import kotlin.math.min

/**
 * author：jiazhijie
 * date：2025/10/21
 * desc：自定义圆角imageView
 * modify record：
 */
class RoundImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private val paint =  Paint(Paint.ANTI_ALIAS_FLAG)
    private val borderPaint =  Paint(Paint.ANTI_ALIAS_FLAG)

    // 路径和矩形
    private val path = Path()
    private val rectF = RectF()

    // 圆角半径数组 [topLeft, topRight, bottomRight, bottomLeft]
    private val radiusArray = FloatArray(8)

    // 属性值
    private var cornerRadius = 0f
    private var topLeftRadius = 0f
    private var topRightRadius = 0f
    private var bottomLeftRadius = 0f
    private var bottomRightRadius = 0f


    private var isCircle = false

    private var borderWidth = 0f
    private var borderColor = Color.TRANSPARENT

    init {
        attrs?.let {
            val typedArray =  context.obtainStyledAttributes(it,R.styleable.RoundImageView)
            cornerRadius = typedArray.getDimension(R.styleable.RoundImageView_roundImageCornerRadius,0f)
            topLeftRadius = typedArray.getDimension(R.styleable.RoundImageView_roundImageTopLeftRadius,cornerRadius)
            topRightRadius = typedArray.getDimension(R.styleable.RoundImageView_roundImageTopRightRadius,cornerRadius)
            bottomLeftRadius = typedArray.getDimension(R.styleable.RoundImageView_roundImageBottomLeftRadius,cornerRadius)
            bottomRightRadius = typedArray.getDimension(R.styleable.RoundImageView_roundImageBottomRightRadius,cornerRadius)
            // 圆形
            isCircle = typedArray.getBoolean(R.styleable.RoundImageView_isCircle, false)

            borderWidth = typedArray.getDimension(R.styleable.RoundImageView_borderWidth,0f)
            borderColor = typedArray.getColor(R.styleable.RoundImageView_borderColor,Color.TRANSPARENT)

            typedArray.recycle()

        }

        setPaint()
        updateRadiusArray()
    }


    private fun setPaint(){
        // 设置Xfermode用于裁剪
        paint.isAntiAlias = true

        // 边框画笔
        borderPaint.isAntiAlias = true
        borderPaint.style = Paint.Style.STROKE
        borderPaint.strokeWidth = borderWidth
        borderPaint.color = borderColor
    }

    private fun updateRadiusArray() {
        // 每个角需要两个值 (x半径, y半径)
        radiusArray[0] = topLeftRadius
        radiusArray[1] = topLeftRadius
        radiusArray[2] = topRightRadius
        radiusArray[3] = topRightRadius
        radiusArray[4] = bottomRightRadius
        radiusArray[5] = bottomRightRadius
        radiusArray[6] = bottomLeftRadius
        radiusArray[7] = bottomLeftRadius
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 如果没有设置圆角也不是圆形，直接调用父类绘制
        if (!isCircle && cornerRadius == 0f &&
            topLeftRadius == 0f && topRightRadius == 0f &&
            bottomLeftRadius == 0f && bottomRightRadius == 0f) {
            super.onDraw(canvas)
            return
        }


        try {
            // 保存画布状态
            val saveCount = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)

            // 先绘制原始图片
            super.onDraw(canvas)

            // 设置混合模式进行裁剪
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN)

            // 绘制裁剪路径
            if (isCircle) {
                drawCirclePath(canvas)
            } else {
                drawRoundRectPath(canvas)
            }

            // 清除混合模式
            paint.xfermode = null

            // 恢复画布
            canvas.restoreToCount(saveCount)

            // 绘制边框
            if (borderWidth > 0 && borderColor != Color.TRANSPARENT) {
                drawBorder(canvas)
            }

        } catch (e: Exception) {
            if (isInEditMode) {
                e.printStackTrace()
                super.onDraw(canvas)
            } else {
                throw e
            }
        }
    }

    private fun drawCirclePath(canvas: Canvas) {
        val centerX = width / 2f
        val centerY = height / 2f
        val radius = min(width, height) / 2f - borderWidth / 2

        canvas.drawCircle(centerX, centerY, radius, paint)
    }

    private fun drawRoundRectPath(canvas: Canvas) {
        path.reset()
        val halfBorder = borderWidth / 2
        rectF.set(
            halfBorder,
            halfBorder,
            width - halfBorder,
            height - halfBorder
        )
        path.addRoundRect(rectF, radiusArray, Path.Direction.CW)
        canvas.drawPath(path, paint)
    }

    private fun drawBorder(canvas: Canvas) {
        if (isCircle) {
            drawCircleBorder(canvas)
        } else {
            drawRoundRectBorder(canvas)
        }
    }

    private fun drawCircleBorder(canvas: Canvas) {
        val centerX = width / 2f
        val centerY = height / 2f
        val radius = min(width, height) / 2f - borderWidth / 2

        canvas.drawCircle(centerX, centerY, radius, borderPaint)
    }

    private fun drawRoundRectBorder(canvas: Canvas) {
        path.reset()
        val halfBorder = borderWidth / 2
        rectF.set(
            halfBorder,
            halfBorder,
            width - halfBorder,
            height - halfBorder
        )
        path.addRoundRect(rectF, radiusArray, Path.Direction.CW)
        canvas.drawPath(path, borderPaint)
    }

    // ========== 公开方法：动态设置属性 ==========

    /**
     * 设置统一圆角
     */
    fun setCornerRadius(radius: Float) {
        this.cornerRadius = radius
        this.topLeftRadius = radius
        this.topRightRadius = radius
        this.bottomLeftRadius = radius
        this.bottomRightRadius = radius
        this.isCircle = false
        updateRadiusArray()
        invalidate()
    }

    /**
     * 分别设置四个角的圆角
     */
    fun setCornerRadius(topLeft: Float, topRight: Float, bottomRight: Float, bottomLeft: Float) {
        this.topLeftRadius = topLeft
        this.topRightRadius = topRight
        this.bottomRightRadius = bottomRight
        this.bottomLeftRadius = bottomLeft
        this.isCircle = false
        updateRadiusArray()
        invalidate()
    }

    /**
     * 设置为圆形
     */
    fun setCircle(isCircle: Boolean) {
        this.isCircle = isCircle
        invalidate()
    }

    /**
     * 设置边框
     */
    fun setBorder(width: Float, color: Int) {
        this.borderWidth = width
        this.borderColor = color
        borderPaint.strokeWidth = width
        borderPaint.color = color
        invalidate()
    }


}